﻿using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;

namespace DailyApp.WPF.HttpClients
{
    /// <summary>
    /// 调用Api的工具类
    /// </summary>
    class HttpRestClient
    {
        //用于发送请求的客户端
        private readonly RestClient Client;

        //固定的uri
        private readonly string baseUrl = "http://localhost:30811/api/";


        /// <summary>
        /// 构造函数
        /// </summary>
        public HttpRestClient()
        {
            Client = new RestClient();//实例化
        }

        /// <summary>
        /// 异步请求调用Api
        /// </summary>
        /// <param name="request">请求的数据</param>
        /// <returns>返回的数据结果（包含调用信息）</returns>
        public async Task<ApiResponse> ExecuteAsync(ApiRequest apiRequest)
        {
            //1.配置请求基本信息--请求类型--请求方式--请求参数
            //请求
            RestRequest restRequest = new RestRequest(apiRequest.Method);//请求方式
            restRequest.AddHeader("Content-Type", apiRequest.ContentType);//请求类型

            //处理参数
            if (apiRequest.Parameters != null)
            {
                //注:参数的传递接收均需要转换为json格式--序列化:对象->json
                var jsonParameters = JsonConvert.SerializeObject(apiRequest.Parameters);//使用第三方插件
                restRequest.AddParameter("param", jsonParameters, ParameterType.RequestBody);
            }


            //2.注册请求地址
            string myUrl = baseUrl + apiRequest.Route;
            Client.BaseUrl = new Uri(myUrl);


            //3.发送请求
            var res = await Client.ExecuteAsync(restRequest);

            //4.请求成功后处理
            if (res.StatusCode == System.Net.HttpStatusCode.OK)
            {
                //json转换为ApiResponse后返回--反序列化:json->对象
                return JsonConvert.DeserializeObject<ApiResponse>(res.Content);
            }
            else
            {
                return new ApiResponse() { ResultCode = -99, ResultMsg = "服务器忙！请稍后" };
            }
        }
    }
}
